//
//  CXHistoryViewController.m
//  ProjectOfBStage
//
//  Created by cuixin on 15/11/25.
//  Copyright © 2015年 cuixin. All rights reserved.
//

#import "CXHistoryViewController.h"
#import "DatabaseHandler.h"
#import "CXSelectSaveTableViewCell.h"
#import <SDWebImageManager.h>
#import <UIImageView+WebCache.h>
#import "LDY_PlayViewController.h"
#import "CoreDataManager.h"
#import "FZ_Dounment.h"
#define kWidth self.view.frame.size.width
#define kHeight self.view.frame.size.height

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

#define WIDTH_PRO(X) (X)*(SCREEN_WIDTH/375)

#define HEIGHT_PRO(Y) (Y)*(SCREEN_HEIGHT/667)

@interface CXHistoryViewController ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, retain)UIView *backView;
@property(nonatomic, retain)NSMutableArray *historyArray;
@property(nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSArray *tempArray;
@property (nonatomic, retain)CoreDataManager *manager;
@property (nonatomic ,retain)NSMutableArray *array;

@end

@implementation CXHistoryViewController
-(void)dealloc{
    [_historyArray release];
    [_tableView release];
    [_backView release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.historyArray = [[NSMutableArray alloc]init];
    self.array = [NSMutableArray array];
    self.manager = [CoreDataManager shareManager];
    [self searchHistory];


    [self createNavigationBar];

//    self.historyArray = [[DatabaseHandler shareDatabaseHandler] selectHistoryHome];
    if (self.historyArray.count == 0 ) {
        UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"history.jpg"]];
        
        image.frame = CGRectMake(0, 0, kWidth, kHeight);
        [self.view addSubview:image];
        [image release];
    }

    [self createTableView];
    
}
-(void)createTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(WIDTH_PRO(0), HEIGHT_PRO(50), WIDTH_PRO(375), HEIGHT_PRO(600)) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    [_tableView release];
    
}
-(void)createNavigationBar{
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWidth, HEIGHT_PRO(50))];
    self.backView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.backView];

    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(WIDTH_PRO(10), HEIGHT_PRO(25), WIDTH_PRO(20), HEIGHT_PRO(20));
    [backButton setBackgroundImage:[UIImage imageNamed:@"gobackbtn@2x"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:backButton];
    
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH_PRO(150), backButton.frame.origin.y, WIDTH_PRO(100), backButton.frame.size.height)];
    titleLable.font = [UIFont systemFontOfSize:HEIGHT_PRO(14)];
    [titleLable setText:@"历史记录"];
    [titleLable setTextColor:[UIColor whiteColor]];
    [self.backView addSubview:titleLable];
    
    UIButton *deleteAllButton = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteAllButton.frame = CGRectMake(kWidth - WIDTH_PRO(60), titleLable.frame.origin.y, WIDTH_PRO(60), titleLable.frame.size.height);
    [deleteAllButton addTarget:self action:@selector(deleteAlll:) forControlEvents:UIControlEventTouchUpInside];
    [deleteAllButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    deleteAllButton.titleLabel.font = [UIFont systemFontOfSize:HEIGHT_PRO(12)];
    [deleteAllButton setTitle:@"删除全部" forState:UIControlStateNormal];
    [self.backView addSubview:deleteAllButton];
    
    
    [titleLable release];
    [self.backView release];
}
-(void)deleteAlll:(UIButton *)button{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
    }else{
        for (FZ_Dounment *list in fetchedObjects) {
            [self.manager.managedObjectContext deleteObject:list];
        }
    }
    [self.manager saveContext];
    self.historyArray = nil;
    [self.tableView reloadData];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return self.historyArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"CXSelectSaveTableViewCellID";
    CXSelectSaveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[CXSelectSaveTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    cell.titleLabel.text = [[self.historyArray objectAtIndex:indexPath.row] name];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:[[self.historyArray objectAtIndex:indexPath.row] pic]] placeholderImage:[UIImage imageNamed:@"wait.png"]];
    return cell;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return HEIGHT_PRO(110);
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [[LDY_PlayViewController sharePlayer] setData:self.historyArray row:indexPath.row];
    LDY_PlayViewController *playController = [LDY_PlayViewController sharePlayer];
    
    playController.playUrl = [[self.historyArray objectAtIndex:indexPath.row] source];
    playController.name = [[self.historyArray objectAtIndex:indexPath.row] name];
    playController.pic = [[self.historyArray objectAtIndex:indexPath.row] pic];
    playController.allMusicArray = self.historyArray;
    [self.navigationController popViewControllerAnimated:YES];

}
// 可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
// 编辑状态
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewCellEditingStyleDelete;
}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    //设置tableview的编辑状态 让编辑按钮的状态与tableview的编辑状态同步
    [self.tableView setEditing:editing animated:animated];
    
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"sf");
    }else{
        for (FZ_Dounment *list in fetchedObjects) {
            if ([list.name isEqualToString:[[self.historyArray objectAtIndex:indexPath.row] name]]) {
                [self.manager.managedObjectContext deleteObject:list];
            }
        }
    }
    [self.manager saveContext];
    
    [self.historyArray removeObjectAtIndex:indexPath.row];
    
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];
    

   [self.tableView reloadData];

}


#pragma mark 返回按钮
-(void)backButtonAction:(UIButton *)button{
    
    [self.navigationController popViewControllerAnimated:NO];
}
-(void)searchHistory{
    if (self.historyArray != nil) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"FZ_Dounment" inManagedObjectContext:self.manager.managedObjectContext];
        [fetchRequest setEntity:entity];
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name"
                                                                       ascending:YES];
        [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        NSError *error = nil;
        NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        self.historyArray = [NSMutableArray arrayWithArray:fetchedObjects];

//        NSSet *set= [NSSet setWithArray:self.historyArray];
//        NSLog(@"%ld %ld", self.historyArray.count, set.count);
//        for (FZ_Dounment *model in set) {
//            [self.array addObject:model];
//            [model release];
//        }
        
        if (fetchedObjects == nil) {
            
        }else{
            
        }
    }
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self searchHistory];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
